//
//  HHVoiceMessageCellData.m
//  HHChatKit
//
//  Created by Henry on 2021/6/3.
//

#import "HHVoiceMessageCellData.h"
#import <AVFoundation/AVFoundation.h>
#import <HHNetworkHelper/HHNetworkHelper.h>
#import <HHTool/HHTool.h>
#import "HHResources.h"
#import "HHChatHelper.h"

@interface HHVoiceMessageCellData () <AVAudioPlayerDelegate>

@property AVAudioPlayer *audioPlayer;

@end

@implementation HHVoiceMessageCellData

- (instancetype)initWithDirection:(HHMsgDirection)direction {
    self = [super initWithDirection:direction];
    if (self) {
        if (direction == HHMsgDirectionIncoming) {
            _voiceImage = [HHResources getImageFromMessage:@"message_voice_receiver_normal"];
       
            _voiceAnimationImages = [NSArray arrayWithObjects:
                                     [HHResources getImageFromMessage:@"message_voice_receiver_playing_1"],
                                     [HHResources getImageFromMessage:@"message_voice_receiver_playing_2"],
                                     [HHResources getImageFromMessage:@"message_voice_receiver_playing_3"], nil];
            
            _textColor = [UIColor hh_colorWithLightColor:[UIColor blackColor] darkColor:[UIColor whiteColor]];

        } else {
            _voiceImage = [HHResources getImageFromMessage:@"message_voice_sender_normal"];
            _voiceAnimationImages = [NSArray arrayWithObjects:
                                     [HHResources getImageFromMessage:@"message_voice_sender_playing_1"],
                                     [HHResources getImageFromMessage:@"message_voice_sender_playing_2"],
                                     [HHResources getImageFromMessage:@"message_voice_sender_playing_3"], nil];
            
            _textColor = [UIColor hh_colorWithLightColor:[UIColor blackColor] darkColor:[UIColor blackColor]];

        }
        
        _textFont = [UIFont systemFontOfSize:12];
        
    }
    return self;
}

+ (NSString *)reuseIdentifier {
    return @"HHVoiceMessageCell";
}

- (CGSize)contentSize {
    CGFloat widthMax = [UIScreen mainScreen].bounds.size.width / 2 - 80;

    CGFloat bubbleWidth = 80 + widthMax / 60 * self.duration;

    CGFloat bubbleHeight = 40;
    if (self.direction == HHMsgDirectionIncoming) {
        bubbleWidth = MAX(bubbleWidth, [HHBubbleMessageCellData incommingBubble].size.width);
        bubbleHeight = [HHBubbleMessageCellData incommingBubble].size.height;
    } else {
        bubbleWidth = MAX(bubbleWidth, [HHBubbleMessageCellData outgoingBubble].size.width);
        bubbleHeight = [HHBubbleMessageCellData outgoingBubble].size.height;
    }
    return CGSizeMake(bubbleWidth, bubbleHeight);
}

- (NSString *)getVoiceFileName {
    if (!self.uuid) {
        NSAssert(NO, @"必须先设置uuid");
    }
    NSString *name = self.uuid;
    if (self.type) {
        name = [NSString stringWithFormat:@"%@.%@", name, self.type];
    }
    return name;
}

- (NSString *)getVoicePath {
    if (!self.conversationId) {
        NSAssert(NO, @"必须设置conversationId，方便管理会话文件");
    }
    return [HHChatHelper pathConvVoice:self.conversationId name:[self getVoiceFileName]];
}

- (void)playVoiceMessage {
    if (self.isPlaying) {
        [self stopVoiceMessage];
        return;
    }
    self.isPlaying = YES;

    // 已播放
    self.played = YES;
    
    NSString *path = [self getVoicePath];
    BOOL isExist = [HHPathTool isExistFile:path];

    if (isExist) {
        [self playInternal:path];
    } else {
        if (self.isDownloading) {
            return;
        }
        // 网络下载
        if (self.url.length == 0) {
            [HHToastTool show:GetHCLocalizableString(@"VoiceExpired")];
            [self stopVoiceMessage];
            return;
        }
                
        __weak typeof(self) ws = self;
        [self downloadVoice:path progress:^(NSUInteger progress) {
            
        } succ:^{
            ws.isDownloading = NO;
            [ws playInternal:path];
        } fail:^(int code, NSString * _Nonnull msg) {
            ws.isDownloading = NO;
            [ws stopVoiceMessage];
        }];
    }
}


- (void)downloadVoice:(NSString *)path progress:(HHDownloadProgress)progress succ:(HHSucc)succ fail:(HHFail)fail {
    [HHNetworkHelper downloadWithURL:self.url filePath:path progress:^(int64_t completedCount, int64_t totalCount) {
        
        CGFloat received = (CGFloat)completedCount;
        NSUInteger pp = (NSUInteger)(received/totalCount * 100);
       
        if (progress) {
            progress(pp);
        }
    } success:^(NSString * _Nonnull filePath) {
        if (succ) {
            succ();
        }
    } failure:^(NSError * _Nonnull error) {
        [HHToastTool show:GetHCLocalizableString(@"VoiceExpired")];
        if (fail) {
            fail(10001, @"server download fail");
        }
    }];
}

- (void)stopVoiceMessage {
    if ([self.audioPlayer isPlaying]) {
        [self.audioPlayer stop];
        self.audioPlayer = nil;
    }
    self.isPlaying = NO;
}

- (void)playInternal:(NSString *)path {
    if (!self.isPlaying)
        return;

    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    NSURL *url = [NSURL fileURLWithPath:path];
    self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
    self.audioPlayer.delegate = self;
    [self.audioPlayer play];

}

#pragma mark - AVAudioPlayerDelegate

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
    self.isPlaying = NO;
}

- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error {
    [HHToastTool show:error.description];
    self.isPlaying = NO;
}

@end
